package com.example.leetcode.design.listener.basic;

import com.google.common.util.concurrent.MoreExecutors;

import java.util.List;
import java.util.concurrent.Executor;

public class MyEventBus {

    private Executor executor;

    private ObserverRegistry registry = new ObserverRegistry();

    public MyEventBus(){
        this(MoreExecutors.directExecutor());
    }


    protected MyEventBus(Executor executor){
        this.executor = executor;
    }

    public void register(Object o){
        registry.register(o);
    }


    public void post(Object event){
        List<ObserverAction> matchedObserverActions = registry.getMatchedObserverActions(event);
        for (ObserverAction action:matchedObserverActions) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    action.execute(event);
                }
            });
        }
    }
}
